import { MenuRoutesType } from '@/interface/route/menuRoutes'
import { cloneDeep } from 'lodash-es'
import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'

export const useMenuStore = defineStore(
    'menu',
    () => {

        const router = useRouter()
        const menuList = ref<MenuRoutesType[]>([])

        const initMenu = (routes: RouteRecordRaw[]): MenuRoutesType[] => {
            let menus: MenuRoutesType[] = []
            if (routes && routes.length > 0) {
                menus = routes.filter((route: RouteRecordRaw) => route.meta && route.meta.order).map((route: RouteRecordRaw) => {
                    let menu: MenuRoutesType = {
                        path: '',
                        label: '',
                        icon: null,
                        key: 999,
                    }
                    if (route.meta) {
                        menu.path = route.path
                        menu.key = route.meta.order
                        menu.label = (route.meta.navTitle || route.meta?.title || '') as string
                        menu.icon = route.meta.icon
                        if (route.children && route.children.length > 1) {
                            menu.children = initMenu(route.children!)
                        }
                    }
                    return menu
                })

                return menus
            } else {
                return []
            }
        }

        const AddMenuRoutes = () => {
            const routes = cloneDeep(router.options.routes)
            let navigationRoutes = []
            let menuRoutes = []
            navigationRoutes = routes.filter((route: RouteRecordRaw) => {
                if (route.meta && Reflect.has(route.meta, 'isSidebar')) {
                    return route
                }
            })
            menuRoutes = initMenu(navigationRoutes)
            menuList.value = menuRoutes.sort((a, b) => a.key - b.key)
        }
        return {
            menuList,
            AddMenuRoutes
        }
    }
)